//
//  WSMainViewControllerViewController.swift
//  微校园
//
//  Created by Gao on 16/12/12.
//  Copyright © 2016年 weSchool. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 主控制器
class WSMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let window :UIWindow = UIApplication.shared.keyWindow!
        window.rootViewController = self;
        window.makeKeyAndVisible()
        
        setupChildControllers()
        
        // 设置新特性视图
        // FIXME
        
        // 注册通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(userLogin),
            name: NSNotification.Name(rawValue: WSUserShouldLoginNotification),
            object: nil)
    }
    
    deinit {
        // 注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: - 监听方法
    @objc private func userLogin(n: Notification) {
        
//        print("用户登录通知 \(n)")
        
        var when = DispatchTime.now()
        
        // 判断 n.object 是否有值 -> token 过期，提示用户重新登录
        if n.object != nil {
            
            // 设置指示器渐变样式
            SVProgressHUD.setDefaultMaskType(.gradient)
            
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录")
            
            // 修改延迟时间
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
//            
//            // FixMe: 展现登录控制器 - 通常会和 UINavigationController 连用，方便返回
//            let nav = UINavigationController(rootViewController: WBOAuthViewController())
//            
//            self.present(nav, animated: true, completion: nil)
        }
    }
}







// MARK: - 设置界面
fileprivate extension WSMainViewController {

    /// 设置所有子控制器
    func setupChildControllers() {
        // 0. 获取沙盒 json 路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        // 加载 data
        var data = NSData(contentsOfFile: jsonPath)
        
        // 判断 data 是否有内容，如果没有，说明本地沙盒没有文件
        if data == nil {
            // 从 Bundle 加载 data
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            
            data = NSData(contentsOfFile: path!)
        }
        
        // data 一定会有一个内容，反序列化
        // 反序列化转换成数组
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]
            else {
                return
        }
        
        //统一导航条样式
        let textAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 19.0), NSForegroundColorAttributeName: UIColor.white]
        UINavigationBar.appearance().titleTextAttributes = textAttributes
        UINavigationBar.appearance().tintColor = UIColor.white
        UINavigationBar.appearance().barTintColor = UIColor.red
        
        // 遍历数组，循环创建控制器数组
        var arrayM = [UIViewController]()
        for dict in array! {
            guard let controller = controller(dict: dict) else {return}
            arrayM.append(controller)
        }
        
        // 设置 tabBar 的子控制器
        viewControllers = arrayM
        
    }
    
    func controller(dict: [String: AnyObject]) -> UIViewController? {
        
        // 1. 取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String
            else { return nil}
        
        let clsWSBase = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WSBaseViewController.Type
        let clsRcBase = NSClassFromString(Bundle.main.namespace + "." + clsName) as? RCConversationListViewController.Type
        
        var cls : UIViewController.Type?
        if clsWSBase != nil {
            cls = clsWSBase
        }
        if clsRcBase != nil {
            cls = clsRcBase
        }
        
        guard let clsTarget = cls else {
            return UIViewController()
        }
        
        // 2. 创建视图控制器
        let vc = clsTarget.init()
        
        vc.title = title
        
        // 3. 设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        // 4. 设置 tabbar 的标题字体（大小）
        vc.tabBarItem.setTitleTextAttributes(
            [NSForegroundColorAttributeName: UIColor.orange],
            for: .highlighted)
        // 系统默认是 12 号字，修改字体大小，要设置 Normal 的字体大小
        vc.tabBarItem.setTitleTextAttributes(
            [NSFontAttributeName: UIFont.systemFont(ofSize: 12)],
            for: UIControlState(rawValue: 0))
        

        
        // 实例化导航控制器的时候，会调用 push 方法将 rootVC 压栈
        return UINavigationController(rootViewController: vc)
    }
}




